package com.yym.ssh;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;

public class ChangePasswd {

	private static String host = "192.168.198.143";
	private static String username = "root";
	private static String password = "1";
	private Connection conn = null;
	private Session session = null;
	private InputStream in = null;
	private InputStream errin = null;
	private OutputStream out = null;

	public ChangePasswd(String host, String username, String password) {
		super();
		this.host = host;
		this.username = username;
		this.password = password;

		conn = new Connection(host);

		try {
			conn.connect();
			boolean isAuthentied = conn.authenticateWithPassword(username,
					password);
			if (!isAuthentied) {

				System.out.println("Authenticated failed...");
			}

		} catch (IOException e) {
			System.err.println("error");
		}

	}

	private Session getSesion() {

		try {
			session=conn.openSession();
			session.startShell();
			session.requestPTY("last");
			return session;
			
		} catch (IOException e) {
			return null;
		}
	}

	private void executeCommand(String command) {
		if (session == null) {
			session = getSesion();
		}
		try {
			session.execCommand(command);
			in = session.getStdout();
			errin = session.getStderr();
			byte[] inbuffer = new byte[500];
			byte[] errinbuffer = new byte[500];
			int inbufferlength = 0;
			int errinbufferlength = 0;
			inbufferlength = in.read(inbuffer);
			errinbufferlength = errin.read(errinbuffer);

			if (inbufferlength != -1) {
				
				System.out.println(new String(inbuffer, 0, inbufferlength));
			}
			if (errinbufferlength != -1) {
				System.out
						.println(new String(errinbuffer, 0, errinbufferlength));

			}

		} catch (IOException e) {
			System.err.println("execute command error!!!");
			e.printStackTrace();
		}

	}

	public void testOpt() {
//		executeCommand("cd /usr");
//		executeCommand("cd /usr/ &&ls -l");

	}

	public static void main(String[] args) {
		new ChangePasswd(host, username, password).testOpt();
	}

}
